import React, { useState, useEffect } from 'react';
import request from '../../../http';
import { DatePicker, Space, Form, Popconfirm } from 'antd';
import { Select } from 'antd';
import { Button, Menu, Dropdown } from 'antd';
const { RangePicker } = DatePicker;
import { Table } from 'antd';
import { history } from 'umi';
const { Option } = Select;
import '../work/arrange.css';
// 冯小建--查询作业-老师

const Arrange = () => {
  const columns = [
    {
      title: '发布时间',
      dataIndex: 'releaseDateTime',
      width: 140,
    },
    {
      title: '项目名字',
      dataIndex: 'courseName',
      width: 120,
    },
    {
      title: '作业主题',
      dataIndex: 'workTheme',
    },
    {
      title: '作业类型',
      dataIndex: 'type',
      width: 90,
    },
    {
      title: '实训老师',
      dataIndex: 'teacherName',
      width: 90,
    },
    {
      title: '计划完成时间',
      dataIndex: 'completionDateTime',
      width: 140,
    },
    {
      title: '小组',
      dataIndex: 'projectGrupName',
    },
    {
      title: '学生总数',
      width: 90,
      render: (text, record) => (
        <Space size="middle">
          {record.toBeSubmit + record.toBeApproved + record.approved}
        </Space>
      ),
    },
    {
      title: '待提交',
      dataIndex: 'toBeSubmit',
      width: 80,
    },
    {
      title: '待批复',
      dataIndex: 'toBeApproved',
      width: 80,
    },
    {
      title: '已批复',
      dataIndex: 'approved',
      width: 80,
    },
    {
      title: '操作',
      key: 'operation',
      dataIndex: 'address',
      fixed: 'right',
      width: 120,
      render: (text, record) => (
        <Space size="middle">
          {/* <a>查看</a> */}
          {/* <a onClick={deleteWork.bind(this,record.workId)}>删除</a> */}
          <Popconfirm
            title="确定要删除吗?"
            onConfirm={deleteWork.bind(this, record.workId)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <a href="#">删除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];
  const startFormData = {
    annex_id: 0,
    completion_time: '',
    course_id: 0,
    p_g_id: '',
    release_time: '',
    s_id: '',
    submitTime: '',
    teacherId: '',
    type: 0,
    work_content: '',
    work_theme: '',
  };
  // 表单
  const [form] = Form.useForm();
  const [submitForm, setSubmitForm] = useState(startFormData);
  // 表单初始查询值
  const [teacherList, setTeacher] = useState<any>([]); //实训老师
  const [teacherAppovalList, setTeacherAppovalList] = useState<any>([]); //责任老师
  const [projectName, setProjectName] = useState<any>([]); //项目名
  const [grouptName, setGrouptName] = useState<any>([]); //小组名
  const [workType, setWorkType] = useState<any>([]); //作业类型

  // 链接查询
  const [courseId, setCourseId] = useState();

  //表格
  const [tableData, setTableData] = useState([]);
  // 表格页码
  const [sum, setSum] = useState(0); //表格数据总条数
  const [page, setPage] = useState(1); //页码
  const [sumPage, setSumPage] = useState(1); //总页数
  const [number, setNumber] = useState(10); //每页数量
  const [paginationData, setPaginationData] = useState();
  // 表格页码
  const pagination = {
    simple: false,
    current: page,
    total: sum,
    pageSizeOptions: ['10', '20', '30'],
    showSizeChanger: true,
    pageSize: number,
    showTotal: (count = sum) => {
      return '共' + count + '条数据';
    },
    onChange: (page, pageSize) => {
      console.log(page, pageSize);
      setPage(page);
      setNumber(pageSize);
      getTableInfo();
    },
    onShowSizeChange: (pageSize) => {
      setNumber(pageSize);
      getTableInfo();
    },
  };

  // 获取表单初始查询值接口
  const getFormInfo = () => {
    console.log('执行-获取表单初始查询值接口-getFormInfo');
    // 查询实训老师
    request
      .post('/common/a_t_s/queryTrainingTeacherNames')
      .then((response) => {
        console.log(response);
        // 判断
        if (response.code === 20000) {
          // 成功
          // console.log(response.data);
          setTeacher(response.data); //设置老师值
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
    // 查询责任老师
    request
      .post('/common/a_t_s/queryResponsibilityName')
      .then((response) => {
        console.log(response);
        // 判断
        if (response.code === 20000) {
          // 成功
          // console.log(response.data);
          setTeacherAppovalList(response.data); //设置老师值
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });

    // 查询项目名
    request
      .post('/homework/teacher/selectCourse_DropDownBox')
      .then((response) => {
        console.log('课程', response);
        // 判断
        if (response.code === 20000) {
          // 成功
          // console.log(response.data);
          setProjectName(response.data); //设置项目名值
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const getGroupNames = () => {
    // 查询小组名
    request
      .post('/homework/teacher/selectGroup_DropDownBox', {
        course_id: courseId,
      })
      .then((response) => {
        console.log(response);
        // 判断
        if (response.code === 20000) {
          console.log('小组名');
          setGrouptName(response.data); //设置小组
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };

  // 获取表格初始值
  const getTableInfo = () => {
    console.log(number, page);
    // 作业列表
    console.log('执行-获取表格值接口-教师下发作业列表-getTableInfo');
    request
      .post('/homework/teacher/selectHomework', {
        number: number,
        page: page,
        ...submitForm,
      })
      .then((response) => {
        console.log(response);
        // 判断
        if (response.code === 20000) {
          // 成功
          console.log('getTableInfo', response.data);
          //设置表格值
          setTableData(response.data.returnDate);
          //设置页码信息
          const paginationData = response.data.paginationData;
          setPaginationData(paginationData);
          setNumber(paginationData.number);
          setSum(paginationData.sum);
          setPage(paginationData.currentPage);
          setSumPage(paginationData.sumPage);
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
    setSubmitForm(startFormData);
  };

  // 选择项目
  const changeCourse = (course_id) => {
    console.log(course_id);
    setCourseId(course_id);
    getGroupNames();
  };

  // 查询改变
  const doChangeTableData = () => {
    getTableInfo();
  };

  // 查询
  const onFinish = (fieldsValue: any) => {
    const release_time = fieldsValue['release_time']
      ? fieldsValue['release_time'].format('YYYY-MM-DD 00:00:00')
      : '';
    const completion_time = fieldsValue['completion_time']
      ? fieldsValue['completion_time'].format('YYYY-MM-DD 00:00:00')
      : '';
    const values = {
      // ...fieldsValue,
      release_time: release_time,
      completion_time: completion_time,
      p_g_id: fieldsValue['p_g_id'] || '',
      s_id: fieldsValue['s_id'] ? fieldsValue['s_id'].toString() : '',
      course_id: fieldsValue['course_id'] || 0,
      teacherId: fieldsValue['teacherId']
        ? fieldsValue['teacherId'].toString()
        : '',
      work_theme: fieldsValue['work_theme'] || '',
      type: parseInt(fieldsValue['type']) || 0,
    };
    setSubmitForm(values);
    console.log('Received values of form: ', fieldsValue, values);
    // 调用查询接口
    doChangeTableData();
  };

  // 重置
  const onReset = () => {
    setSubmitForm(startFormData);
    form.resetFields();
  };

  // 删除作业操作
  const deleteWork = (workId) => {
    console.log('删除作业');
    request
      .post('/homework/teacher/deleteHomework', {
        workId: workId,
      })
      .then((response) => {
        console.log(response);
        // 判断
        if (response.code === 20000) {
          // 成功
          getTableInfo(); //重新加载
        } else {
          alert(response.message);
        }
      })
      .catch((error) => {
        console.log(error);
      });
  };
  const cancel = (e) => {
    console.log(e);
    // message.error('取消删除');
  };

  //页面加载
  useEffect(() => {
    // 获取初始查询值
    getFormInfo();
    getTableInfo();
  }, []);

  return (
    <div>
      {/* 查询表单 */}
      <Form
        form={form}
        name="time_related_controls"
        className="absence-form my-form"
        onFinish={onFinish}
        layout="inline"
      >
        <Form.Item className="form-item" name="release_time" label="发布时间">
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item className="form-item" name="course_id" label="项目名字">
          <Select
            className="sel"
            size="middle"
            placeholder="请选择"
            onChange={changeCourse.bind(this)}
          >
            {projectName.map((item: any, i: number) => {
              return (
                <Option value={item.id} key={i}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item className="form-item" name="teacherId" label="实训老师">
          <Select className="sel" size="middle" placeholder="请选择">
            {teacherList.map((item: any, i: number) => {
              return (
                <Option value={item.id} key={i}>
                  {item.format}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item className="form-item" name="s_id" label="责任老师">
          <Select className="sel" size="middle" placeholder="请选择">
            {teacherAppovalList.map((item: any, i: number) => {
              return (
                <Option value={item.id} key={i}>
                  {item.format}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item
          className="form-item"
          name="completion_time"
          label="计划完成时间"
        >
          <DatePicker style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item className="form-item" name="p_g_id" label="小组名字">
          <Select className="sel" size="middle" placeholder="请先选择项目名">
            {grouptName.map((item: any, i: number) => {
              return (
                <Option value={item.id} key={i}>
                  {item.name}
                </Option>
              );
            })}
          </Select>
        </Form.Item>

        <Form.Item className="form-item" name="type" label="作业类型">
          <Select placeholder="请选择" size="middle" className="sel">
            <Option value="0">日常作业</Option>
            <Option value="1">阶段性交付作业</Option>
            <Option value="2">最终交付作业</Option>
          </Select>
        </Form.Item>

        <Form.Item
          className="form-item"
          wrapperCol={{
            xs: { span: 24, offset: 0 },
            sm: { span: 16, offset: 8 },
          }}
        >
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button className="reset" htmlType="button" onClick={onReset}>
            重置
          </Button>
        </Form.Item>
      </Form>

      {/* 新增 */}
      <div style={{ margin: '10px' }}>
        <Button
          className="add"
          size="middle"
          type="primary"
          onClick={() => history.push('/teacher/work/addWork')}
        >
          +新增
        </Button>
      </div>
      {/* 表格 */}
      <div>
        <Table
          columns={columns}
          dataSource={tableData}
          scroll={{ x: 1200, y: 300 }}
          pagination={pagination}
        />
      </div>
    </div>
  );
};

export default Arrange;
